import React, { useState, useEffect, FC, SyntheticEvent, ChangeEvent, useRef, MutableRefObject } from 'react'
import {
  Space, Row, Col, Input,
  Form, Table, Modal, Card, InputNumber
} from 'antd'
import type { ColumnsType, ColumnType } from 'antd/es/table'
import XlButtonFC from '@/components/xlbutton/xlbutton'
import XlModalFC from '@/components/xlmodal/xlmodal'
import { Scrollbars } from 'react-custom-scrollbars'
import * as api from '@/api'
import { IData, PagingSize, DictionaryTypeModal, IResponseCodeType, IRoleAdminListModel, IMemberAdminListModel } from '@/models/common'
import { DownOutlinedIcon } from '@/models/icons'
import util from '@/utils/util'
import './roleadmin.scss'
interface ColumnsDataType {
  [name: string]: string
}
export interface IViewModel {
  roleUpdateModalOpen: boolean
  /**
   * 当前修改行信息
   */
  roleUpdateRow: ColumnsDataType
  pageLoading: boolean
  /**
   * 表格数据
   */
  roleTableList: ColumnsDataType[]
  /**
  * 当前页码
  */
  page: number
  /**
   * 每页数量
   */
  pageSize: number
  /**
   * 是否还有下一页
   */
  hasNextPage: boolean

  roleLookModalOpen: boolean
  roleLookRow: ColumnsDataType
  /**
    * 角色成员表格数据
    */
  roleMemberTableList: ColumnsDataType[]
  roleMemberSelectKeys: React.Key[]
  notAuth: boolean
}

const Index: FC = () => {
  const [data, setData] = useState<IData<IViewModel>>({
    ViewModel: {
      roleUpdateModalOpen: false,
      roleUpdateRow: {
        id: "",
        name: "",
      },
      pageLoading: false,
      roleTableList: [],
      page: 1,
      pageSize: PagingSize.PageSize,
      hasNextPage: false,

      roleLookModalOpen: false,
      roleLookRow: {
        id: "",
        name: "",
      },
      roleMemberTableList: [],
      roleMemberSelectKeys: [],
      notAuth: false
    }
  })

  useEffect(() => {
    
  }, [])

  const events = {
    //新增角色
    onClickAddRow() {
      const { ViewModel } = data
      ViewModel.roleUpdateRow.name = ''
      ViewModel.roleUpdateRow.id = ''
      ViewModel.roleUpdateModalOpen = true
      setData({ ...data })
    },
    //编辑角色
    onClickEditRow(_: ColumnsDataType, record: ColumnsDataType, index: number) {
      const { ViewModel } = data
      ViewModel.roleUpdateRow.name = record.name
      ViewModel.roleUpdateRow.id = record.id
      ViewModel.roleUpdateModalOpen = true
      setData({ ...data })
    },
    //查看成员
    onClickLookRow(_: ColumnsDataType, record: ColumnsDataType, index: number) {
      const { ViewModel } = data
      ViewModel.roleLookRow.name = record.name
      ViewModel.roleLookRow.id = record.id
      ViewModel.roleLookModalOpen = true
      setData({ ...data })
      methods.requestRoleMemberList()
    },
    //删除角色
    onClickDeleteRow(_: ColumnsDataType, record: ColumnsDataType, index: number) {
      Modal.confirm({
        title: '删除',
        centered: true,
        closable: true,
        content: '确认删除该角色吗？',
        onOk() {
          return new Promise(async (resolve, reject) => {
            await methods.requestDeleteRole(record.id)
            resolve(null)
          }).catch(() => console.log('Oops errors!'))
        },
        onCancel() {

        },
      })
    },
    onUpdateRoleNameChange(e: ChangeEvent<HTMLInputElement>) {
      const { ViewModel } = data
      ViewModel.roleUpdateRow.name = e.target.value
      setData({ ...data })
    },
    onRoleUpdateRowOk() {
      const { ViewModel } = data
      if (!ViewModel.roleUpdateRow.name) {
        util.alertTip('请输入角色名称')
        return
      }
      if (ViewModel.roleUpdateRow.id) {
        methods.requestUpdateRole()
      } else {
        methods.requestAddRole()
      }
    },
    onRoleUpdateRowCancel() {
      const { ViewModel } = data
      ViewModel.roleUpdateRow.name = ''
      ViewModel.roleUpdateRow.id = ''
      ViewModel.roleUpdateModalOpen = false
      setData({ ...data })
    },
    onRoleLookRowCancel() {
      const { ViewModel } = data
      ViewModel.roleLookRow.name = ''
      ViewModel.roleLookRow.id = ''
      ViewModel.roleLookModalOpen = false
      setData({ ...data })
    },
    onRoleMemberSelectChange(newSelectedRowKeys: React.Key[]) {
      const { ViewModel } = data
      ViewModel.roleMemberSelectKeys = newSelectedRowKeys
      setData({ ...data })
    },
    onClickUnBindRoleMember() {
      const { ViewModel } = data
      if (ViewModel.roleMemberSelectKeys.length == 0) {
        util.alertTip('请先选择解绑人员')
        return
      }
      Modal.confirm({
        title: '解绑人员',
        centered: true,
        closable: true,
        content: '确认解绑所选人员吗？',
        onOk() {
          return new Promise(async (resolve, reject) => {
            await methods.requestUnBindRoleMember()
            resolve(null)
          }).catch(() => console.log('Oops errors!'))
        },
        onCancel() {

        },
      })
    },
    onClickLoadMore() {
      const { ViewModel } = data
      if (ViewModel.hasNextPage) {
        // ViewModel.page = ViewModel.page + 1
        // ViewModel.pageLoading = true
        // setData({ ...data })
        // methods.querySubTableList()
      }
    },
  }
  const methods = {
    /**
     * 加载角色
     */
    async requestRoleList() {
      const { ViewModel } = data
      ViewModel.pageLoading = true
      setData({ ...data })
      let res = await api.common.getRoleAdminList<IRoleAdminListModel>(null)
      const { code, data: roleAdminData, message } = res
      if (code == IResponseCodeType.Success) {
        let { result_list = [] } = roleAdminData
        ViewModel.roleTableList = [...result_list]
        if (result_list.length < ViewModel.pageSize) {
          ViewModel.hasNextPage = false
        } else {
          ViewModel.hasNextPage = false
        }
      } else if (code == IResponseCodeType.NotAuth) {
        ViewModel.notAuth = true
      } else {
        util.alertTip(message)
      }
      ViewModel.pageLoading = false
      setData({ ...data })
    },
    /**
     * 新增角色
     */
    async requestAddRole() {
      const { ViewModel } = data
      let res = await api.common.addRoleAdmin({
        name: ViewModel.roleUpdateRow.name
      })
      const { code, message } = res
      if (code == IResponseCodeType.Success) {
        ViewModel.roleUpdateRow.name = ''
        ViewModel.roleUpdateRow.id = ''
        ViewModel.roleUpdateModalOpen = false
        setData({ ...data })
        methods.requestRoleList()
      } else {
        util.alertTip(message)
      }
    },
    /**
     * 更新角色
     */
    async requestUpdateRole() {
      const { ViewModel } = data
      let res = await api.common.editRoleAdminInfo({
        name: ViewModel.roleUpdateRow.name,
        id: ViewModel.roleUpdateRow.id,
      })
      const { code, message } = res
      if (code == IResponseCodeType.Success) {
        ViewModel.roleUpdateRow.name = ''
        ViewModel.roleUpdateRow.id = ''
        ViewModel.roleUpdateModalOpen = false
        setData({ ...data })
        methods.requestRoleList()
      } else {
        util.alertTip(message)
      }
    },
    /**
     * 删除角色
     * @param id 
     */
    async requestDeleteRole(id: string) {
      let res = await api.common.deleteRoleAdmin<null>({
        id
      })
      const { code, message } = res
      if (code == IResponseCodeType.Success) {
        methods.requestRoleList()
      } else {
        util.alertTip(message)
      }
    },
    /**
     * 加载角色成员列表
     * @param id 
     */
    async requestRoleMemberList() {
      const { ViewModel } = data
      let res = await api.common.getRoleMemberList<IMemberAdminListModel>({
        id: ViewModel.roleLookRow.id
      })
      const { code, data: roleMemberData, message } = res
      if (code == IResponseCodeType.Success) {
        let { result_list = [] } = roleMemberData
        ViewModel.roleMemberTableList = [...result_list]
        ViewModel.roleMemberSelectKeys = []
        setData({ ...data })
      } else {
        util.alertTip(message)
      }
    },
    /**
     * 解绑角色人员
     */
    async requestUnBindRoleMember() {
      const { ViewModel } = data
      let res = await api.common.unBindRoleMember({
        user_ids: JSON.stringify(ViewModel.roleMemberSelectKeys),
        role_id: ViewModel.roleLookRow.id
      })
      const { code, message } = res
      if (code == IResponseCodeType.Success) {
        methods.requestRoleMemberList()
      } else {
        util.alertTip(message)
      }
    },
    createColumns() {
      const columns: ColumnsType<ColumnsDataType> = [
        {
          title: '角色名称',
          align: "left",
          key: 'name',
          dataIndex: 'name',
        },
        {
          title: '操作',
          align: "center",
          key: 'action',
          render: (_, record, index) => (
            <Space size={4}>
              <XlButtonFC type='primary' size='small' onClick={() => events.onClickLookRow(_, record, index)}>
                角色成员
              </XlButtonFC>
              <XlButtonFC type='primary' size='small' onClick={() => events.onClickEditRow(_, record, index)}>
                修改
              </XlButtonFC>
              <XlButtonFC type='primary' size='small' onClick={() => events.onClickDeleteRow(_, record, index)}>
                删除
              </XlButtonFC>
            </Space>
          ),
        }
      ]
      return columns
    },
    createRoleMemberColumns() {
      const columns: ColumnsType<ColumnsDataType> = [
        {
          title: '姓名',
          align: "left",
          key: 'name',
          dataIndex: 'name',
        },
        {
          title: '部门名称',
          align: "left",
          key: 'department_name',
          dataIndex: 'department_name',
        },
      ]
      return columns
    },
    renderPage() {
      if (data.ViewModel.notAuth) {
        return null
      }
      return <>
        <Card title="角色管理">
          <Col className='role-admin-wrap'>
            {/* 按钮操作区域 */}
            <Row align='middle' justify='space-between' className='buttonGroupWrap' gutter={[0, 10]}>
              <Col>
                <Space size={6}>
                  <XlButtonFC type='primary' onClick={events.onClickAddRow}>新增</XlButtonFC>
                </Space>
              </Col>
              <Col className='count'>
                {data.ViewModel.hasNextPage ? '已部分加载' : '已全部加载'}，共{data.ViewModel.roleTableList.length}个
              </Col>
            </Row>
            {/* 表格区域 */}
            <Row className='tableWrap'>
              <Col className={['tableContent', data.ViewModel.hasNextPage ? 'hasTableContent' : 'noTableContent'].join(" ")}>
                <Table
                  scroll={{
                    x: '100%',
                    y: data.ViewModel.hasNextPage ? 'calc(100vh - 355px)' : 'calc(100vh - 280px)'
                  }}
                  loading={data.ViewModel.pageLoading}
                  tableLayout='fixed'
                  rowKey='id'
                  pagination={false}
                  columns={methods.createColumns()}
                  dataSource={data.ViewModel.roleTableList}
                />
              </Col>

              {
                data.ViewModel.hasNextPage ? <Row className='loadmore-wrap' onClick={events.onClickLoadMore}>
                  <Col>点击加载更多</Col>
                  <Row><DownOutlinedIcon className='loadmore-icon' /></Row>
                </Row> : null
              }
            </Row>
          </Col>
        </Card>
        {/* 添加修改弹出框 */}
        <XlModalFC
          open={data.ViewModel.roleUpdateModalOpen}
          onOk={events.onRoleUpdateRowOk}
          onCancel={events.onRoleUpdateRowCancel}
          title='新增/修改'
          destroyOnClose
        >
          <Form
            labelCol={{ span: 5 }}
            wrapperCol={{ span: 17 }}
            autoComplete="off"
          >
            <Form.Item
              label="角色名称"
              required
            >
              <Input value={data.ViewModel.roleUpdateRow.name} onChange={events.onUpdateRoleNameChange} allowClear placeholder='请输入角色名称' />
            </Form.Item>
          </Form>
        </XlModalFC>
        {/* 角色成员表格 */}
        <XlModalFC
          open={data.ViewModel.roleLookModalOpen}
          footer={null}
          title={'【' + data.ViewModel.roleLookRow.name + '】角色成员'}
          destroyOnClose
          width={800}
          onCancel={events.onRoleLookRowCancel}
          className='role-member-xlmodal'
        >
          <Col className='role-admin-wrap role-member-wrap'>
            {/* 按钮操作区域 */}
            <Row align='middle' justify='space-between' className='buttonGroupWrap' gutter={[0, 10]}>
              <Col>
                <Space size={6}>
                  <XlButtonFC type='primary' onClick={events.onClickUnBindRoleMember}>解绑</XlButtonFC>
                </Space>
              </Col>
              <Col className='count'>
                共{data.ViewModel.roleMemberTableList.length}个
              </Col>
            </Row>
            {/* 表格区域 */}
            <Row className='tableWrap'>
              <Col className='tableContent'>
                <Table
                  scroll={{
                    x: '100%',
                    y: 450
                  }}
                  rowKey='user_id'
                  pagination={false}
                  columns={methods.createRoleMemberColumns()}
                  dataSource={data.ViewModel.roleMemberTableList}
                  rowSelection={{
                    selectedRowKeys: data.ViewModel.roleMemberSelectKeys,
                    onChange: events.onRoleMemberSelectChange
                  }}
                />
              </Col>

            </Row>
          </Col>

        </XlModalFC>
      </>
    }
  }
  return methods.renderPage()
}
export default Index
